package com.opennews.openplatform.websocket

import groovy.transform.CompileStatic
import org.springframework.messaging.Message
import org.springframework.messaging.MessageChannel
import org.springframework.messaging.simp.stomp.StompCommand
import org.springframework.messaging.support.ChannelInterceptor
import org.springframework.messaging.simp.stomp.StompHeaderAccessor

/**
 * Channel Interceptors
 * https://docs.spring.io/spring-integration/docs/2.0.0.M2/spring-integration-reference/html/ch03s03.html
 * https://docs.spring.io/spring-framework/reference/web/websocket/stomp/interceptors.html
 */
@CompileStatic
class MyChannelInterceptor implements ChannelInterceptor {
    /**
     * The methods that return a Message instance can be used for transforming the Message or can return 'null' to
     * prevent further processing (of course, any of the methods can throw a RuntimeException).
     */
    @Override
    Message<?> preSend(Message<?> message, MessageChannel channel) {
        def headerAccessor= StompHeaderAccessor.wrap(message)

        // nativeHeaders contains client headers info.
        def nativeHeaders = headerAccessor.messageHeaders["nativeHeaders"]

        if (headerAccessor.command == StompCommand.CONNECT) {
            // If your system only authenticates during connection then you can use connectHeaders to carry auth info from client.
            // stompjs suggests login and passcode.
            // You still can use Authorization like you do in http request.
            // Once authentication failed return null will not to proceed current action.
        } else if (headerAccessor.command == StompCommand.SUBSCRIBE) {
            // If you do authorization on each subscription client can use headers to carry Authorization.
            // Once authorization failed return null will not to proceed current action.
        } else if (headerAccessor.command == StompCommand.SEND) {
            // If you do authorization on each send client can use headers to carry Authorization.
            // Once authorization failed return null will not to proceed current action.
        }

        return message
    }
}
